package com.hc.controller;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.domain.Province;
import com.hc.ex.GlobalException;
import com.hc.service.ProvinceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * @author hc
 * @date 2021/12/27 17:49
 */
@Slf4j
@RestController
@RequestMapping("/province")
public class ProvinceController {

    @Resource
    private ProvinceService provinceService;

    @PostMapping
    public Result create(@RequestBody Province province) {
        boolean res = provinceService.save(province);
        return res ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }

    @PutMapping
    public Result updateById(@RequestBody Province province) {
        boolean res = false;
        try {
            res = provinceService.updateById(province);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(400, e.getMessage());
        }
        return res ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }

    @DeleteMapping("{id}")
    public Result removeById(@PathVariable Serializable id) {
        boolean res = provinceService.removeById(id);
        return res ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
    }

    @GetMapping("{id}")
    public Result getById(@PathVariable Serializable id) {
        Province res = provinceService.getById(id);
        return ResultUtil.success("查询成功").setData(res);
    }

    @GetMapping("/list")
    public Result getAllProince() {
        List<Province> list = provinceService.findAllProvince("all", true);
        return ResultUtil.success("查询成功").setData(list);
    }
}